import Koa from "koa";
import { authRouter } from "./code/directoryInit";
import catchErr from "./code/catchERR";
import koaBody from "koa-body";
import path from "node:path";
import koaStatic from 'koa-static';
import { cwd } from 'node:process';
import { historyApiFallback } from 'koa2-connect-history-api-fallback';
import enforceHttps from "koa-sslify";
import https from 'https';
import fs from 'fs';

const app = new Koa()
app.use(catchErr)
app.use(koaBody({
    multipart: true, //支持图片文件
    formidable: {
        maxFileSize: 1024 * 1024 * 2,
        uploadDir: path.join(cwd(), '/public/uploads'), //设置上传目录
        keepExtensions: true, //保留拓展名
    }
}))
app.use(koaStatic(path.join(cwd(), 'public')))

app.use(enforceHttps())
app.use(historyApiFallback({
    index: '/index.html', whiteList: ['/api']
})).use(koaStatic(path.join(cwd(), 'dist')))

const options = {
    key: fs.readFileSync('./src/ssl/baichx.shop.key'),
    cert: fs.readFileSync('./src/ssl/baichx.shop.pem')
};

authRouter(app).then(() => {
    https.createServer(options, app.callback()).listen(443, () => {
        console.log(`应用实例，访问地址为 https://baichx.shop:443`);
    })
})

// authRouter(app).then(() => {
//     app.listen(3000, () => {
//         console.log(`应用实例，访问地址为 http://localhost:3000`);
//     })
// })